package mysqlDb

import (
	"fmt"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
	"yu.DbSub/src/config"
)

type Mysql struct {
	name     string   //数据库名
	url      string   //url
	user     string   //用户名
	password string   //数据库密码
	db_type  string   //数据库类型
	db       *sqlx.DB //连接句柄
}

var mysql_o *Mysql

func ConnectMysql(n config.Node_info) error {
	str := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8", n.User, n.Password, n.Node_url, n.Database[0])
	dba, err := sqlx.Open(n.Node_db_type, str)
	if err != nil {
		fmt.Printf("数据库连接错误: %v\n", err)
	}
	mysql_o = &Mysql{
		db:       dba,
		name:     n.Node_name,
		url:      n.Node_url,
		user:     n.User,
		password: n.Password,
		db_type:  n.Node_db_type,
	}
	return err
}
func GetMysql() *Mysql {
	return mysql_o
}

func (m Mysql) QueryData(sql string) {
	rows, err := m.db.Query(sql)
	if err != nil {
		fmt.Printf("query faied, error:[%v]", err.Error())
		return
	}
	for rows.Next() {
		//定义变量接收查询数据
		var uid int
		var name string

		err := rows.Scan(&uid, &name)
		if err != nil {
			fmt.Printf("get data failed, error:[%v]", err.Error())
		}
		fmt.Println(uid, name)
	}

	//关闭结果集（释放连接）
	rows.Close()
}

func (m Mysql) InsertData(sql string) {
	rs, err := m.db.Exec(sql)
	if err != nil {
		fmt.Printf("insert faied, error:[%v]", err.Error())
	}
	fmt.Printf("插入数据回应%v\n", rs)
}
